<template>
  <div class="w-75 m-auto mt-4">
    <div v-if="current_user">
      <user-profile :you="user" :user="current_user" @change-role="putRole"></user-profile>
      <div v-if="current_user.role == 'user'">
        <h1>Заявления</h1>
        <view-req :currentPage="currentPage" :customFilterParams="{ user_id: id }" :tokens="tokens"
          :urlBase="'/user/' + id + '/'" :user="user"></view-req>
      </div>
    </div>
    <h3 class="text-danger">{{ error }}</h3>
  </div>
</template>

<script>
import ViewReq from "../components/ViewReq.vue";
import { useFetch } from "@vueuse/core";
import UserProfile from '../components/UserProfile.vue';

export default {
  components: {
    ViewReq, UserProfile,
  },
  props: {
    id: String,
    tokens: Object,
    user: Object,
    currentPage: Number,
  },
  data() {
    return {
      current_user: undefined,
      error: "",
    };
  },
  mounted() {
    this.getUser(this.id, this.tokens.access_token);
  },
  methods: {
    putRole(role) {
      let token = this.tokens.access_token;
      const { data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/users/${this.current_user.id}/${role}`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      ).put();

      onFetchError((error) => {
        this.error += error.message;
      });

      onFetchResponse(() => {
        this.current_user = JSON.parse(data.value);
      });
    },
    // TODO: Добавить логику с фильтрациями, что я реализовал на сервере. В данном случае поиск по теме и по статусу
    getUser(id, token) {
      const { isFetching, data, onFetchError, onFetchResponse } = useFetch(
        `${process.env.VUE_APP_BASE_URI}/users/${id}`,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      )
        .get()
        .json();

      onFetchError((error) => {
        this.error = error.message;
      });

      onFetchResponse(() => {
        this.current_user = data.value;
      });
      return { isFetching };
    },
  },
};
</script>

<style></style>